package com.lagou.client;

import com.lagou.encoder.JSONSerializer;
import com.lagou.encoder.RpcEncoder;
import com.lagou.request.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class RpcConsumer {

    public static final AtomicInteger REQUEST_ID_SEQ = new AtomicInteger();

    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private  UserClientHandler userClientHandler;

    //2.初始化netty客户端
    public void initClient(String hostName, int port) throws InterruptedException {
        userClientHandler = new UserClientHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        // 绑定出参格式为RpcRequest
                        pipeline.addLast(new RpcEncoder<>(RpcRequest.class, new JSONSerializer()));
                        // 绑定入参为String
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
                    }
                });
        bootstrap.connect(hostName, port).sync();

    }

    //1.创建一个代理对象 providerName：UserService#sayHello are you ok?
    @SuppressWarnings("unchecked")
    public <T> T createProxy(final Class<T> serviceClass,String hostName, int port) {
        //借助JDK动态代理生成代理对象
        Object proxyObject = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //（1）调用初始化netty客户端的方法
                if (userClientHandler == null) {
                    initClient(hostName,port);
                }
                RpcRequest request = new RpcRequest();
                String requestId = String.format("%010d", REQUEST_ID_SEQ.addAndGet(1));
                request.setRequestId(requestId);
                request.setClassName(serviceClass.getSimpleName());
                request.setMethodName(method.getName());
                request.setParameters(args);
                request.setParameterTypes(new Class[]{String.class});
                // 设置参数
                userClientHandler.setPara(request);
                // 去服务端请求数据
                Object result = "";
                if (userClientHandler == null){
                    return "";
                }
                try{
                    result = executor.submit(userClientHandler).get(10,TimeUnit.SECONDS);
                }catch (Exception e){
                    System.out.println("远程服务请求失败");
                    result = "fail";
                }
                return result;
            }
        });
        return (T) proxyObject;
    }

    public UserClientHandler getUserClientHandler() {
        return userClientHandler;
    }
}
